<?php
namespace app\Logic\Layui\ServiceProviders;

use app\Logic\Container;
use app\Logic\Logic;
use App\Model\AuthModel;
use App\Model\RoleModel;

class RoleProvider extends Logic implements ServiceProviderInterface
{
    public $app;

    public function __construct(\Closure $app)
    {
        $this->app = $app($this);
    }


    /**
     * @param Container $app
     */
    public static function register(Container $app)
    {
        !isset($app->values['Role']) && $app->values['Role'] = function (\Closure $app){
            return new self($app);
        };
    }


    public function lists()
    {
        $data = $this->app->input();

        $model = new RoleModel();

        $start = start($data['page'], $data['limit']);
        $res = $model->offset($start)->limit($data['limit'])
            ->orderBy('id', 'desc')->get();
        $count = $model->count();

        return ['code' => 0, 'count' => $count, 'data' => $res, 'msg' => ''];
    }


    public function create()
    {
        $data = $this->app->input();

        if(empty($data)){
            throw new \Exception('提交数据为空');
        }

        $data['auth_id'] = isset($data['auth_id']) ? implode(',',$data['auth_id'])  : '';
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        $menuModel = new RoleModel();

        $rules = $menuModel->getRules($data);
        $error = $menuModel->validator($data, $rules);

        if($error){
            throw new \Exception($error);
        }

        $menuModel->insert($data);

    }


    public function edit($id)
    {
        $data = $this->app->input();

        if(empty($data)){
            throw new \Exception('提交数据为空');
        }

        $data['auth_id'] = isset($data['auth_id']) ? implode(',',$data['auth_id'])  : '';
        $data['updated_at'] = date('Y-m-d H:i:s');

        $menuModel = new RoleModel();

        $rules = $menuModel->getRules($data);

        $error = $menuModel->validator($data, $rules);

        if($error){
            throw new \Exception($error);
        }

        $menuModel->where(['id'=>$id])->update($data);
    }


    public function first($id)
    {
        $model = new RoleModel();

        return $model->where(['id'=>$id])->first()->toArray();
    }


    public function delete()
    {
        $ids = $this->app->input('id');

        return RoleModel::destroy($ids);
    }


    /**
     * @param $name
     * @param $arguments
     * @return mixed
     */
    public function __call($name,$arguments)
    {
        return $this->app->$name(...$arguments);
    }
}